:- import "%%/lib/dynamic.sl" #
:- import "%%/lib/t23.sl" #


-- 2-3 Tree Indexing --

transient .name (.v0 => .v1) .query :-
	get .name .v0, .query, set .name .v1 #

index.build .clause .col :-
	getClauseName .clause .clauseName,
	set BUILDING $,
	forall (search .clause) (
		nth .clause .col .key,
		transient BUILDING (.tree => .tree1)
			(addTo23TreeList .key .clause .tree .tree1)
	),
	get BUILDING .built, unset BUILDING,
	insert (INDEX .clauseName .col .built) #

	-- Supposedly unique key
index.buildUnique .clause .col :-
	getClauseName .clause .clauseName,
	set BUILDING $,
	forall (search .clause) (
		nth .clause .col .key,
		transient BUILDING (.tree => .tree1)
			(t23.add .key .clause .tree .tree1)
	),
	get BUILDING .built, unset BUILDING,
	insert (INDEX.UNIQUE .clauseName .col .built) #

index.insert .clause :-
	getClauseName .clause .clauseName,
	forall (delete (INDEX.UNIQUE .clauseName .col .tree)) (
		nth .clause .col .key,
		t23.add .key .clause .tree .tree1,
		insert (INDEX.UNIQUE .clauseName .col .tree1)
	),
	forall (delete (INDEX .clauseName .col .tree)) (
		nth .clause .col .key,
		addTo23TreeList .key .clause .tree .tree1,
		insert (INDEX .clauseName .col .tree1)
	) #

index.search .clause :-
	getClauseName .clause .clauseName,
	searchWithClauseName .clause .clauseName #

searchWithClauseName .clause .clauseName :-
	search (INDEX.UNIQUE .clauseName .col .tree),
	nth .clause .col .key, bound .key !
	t23.search .key .clause .tree #
searchWithClauseName .clause .clauseName :-
	search (INDEX .clauseName .col .tree),
	nth .clause .col .key, bound .key !
	t23.search .key .list .tree !
	list.member .list .clause #

	-- Adds with a non-unique key
addTo23TreeList .key .clause .tree .tree1 :-
	if (t23.search .key .list .tree) then ( -- Key already exists
		t23.replace .key (.clause, .list) .tree .tree1
	) else ( -- Creates new key entry
		t23.add .key (.clause,) .tree .tree1
	) #
